1809F - Traveling in Berland - CodeForces Solution


binary search data structures graphs greedy implementation *2500

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ve vector
#define se second
#define fi first
#define all(x) x.begin(), x.end()
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

ll a[200000], b[200000], pref[400000], last[400000], p[400000], r[400000];


void solve(){
    ll n, k;
    cin >> n >> k;
    bool no1 = 1;

    for(int i = 0; i < n; i++)cin >> a[i];
    for(int i = 0; i < n; i++){
        cin >> b[i];
        if(b[i] == 1)no1 = 0;
    }


    for(int i = 0; i < 2*n; i++){
        r[i] = i%n;
    }

    ll sum = 0;
    for(int i = 0; i < n; i++)sum += a[i];

    ll w = 0;
    ll cost = 0;

    int id = 2*n-1;
    ll path = 0;
    for(int it = 2*n-1; it>=0; it--){
        if(it != 2*n-1){
            path += a[r[it]];
        }

        p[it] = path;
        last[it] = id;

        if(b[r[it]] == 1){
            id = it;
        }
    }

    for(int it = 0; it < 2*n; it++){
        pref[it] = cost - w;
        if(b[r[it]] == 1){
            if(p[it]-p[last[it]] > k){
                cost += k-w;
                w = k;
            }
            else if(p[it]-p[last[it]] > w){
                ll need = p[it]-p[last[it]];
                cost += need;
                w += need;
            }
        }
        else{
            if(w < a[r[it]]){
                ll need = a[r[it]] - w;
                cost += 2*need;
                w += need;
            }
        }
        w -= a[r[it]];
    }

    for(int v = 0; v < n; v++){
        ll ans;
        if(no1){
            ans = 2*sum;
        }
        else if(b[v] == 1){
            ans = pref[v+n] - pref[v];
        }
        else{
            ans = pref[v+n] - pref[last[v]] + 2*(p[v] - p[last[v]]);
        }
        cout << ans << ' ';
    }
    cout << '\n';
}



int main()
{
//    ifstream cin("input.txt");
//    ofstream cout("output.txt");
    ios_base::sync_with_stdio(0);cin.tie(0);

    int t;
    cin >> t;
    while(t--){
        solve();
    }

    return 0;
}


Comments

Submit
0 Comments
More Questions

1025D - Recovering BST
439A - Devu the Singer and Churu the Joker
1323A - Even Subset Sum Problem
1095A - Repeating Cipher
630F - Selection of Personnel
630K - Indivisibility
20B - Equation
600B - Queries about less or equal elements
1015A - Points in Segments
1593B - Make it Divisible by 25
680C - Bear and Prime 100
1300A - Non-zero
1475E - Advertising Agency
1345B - Card Constructions
1077B - Disturbed People
653A - Bear and Three Balls
794A - Bank Robbery
157A - Game Outcome
3B - Lorry
1392A - Omkar and Password
489A - SwapSort
932A - Palindromic Supersequence
433A - Kitahara Haruki's Gift
672A - Summer Camp
1277A - Happy Birthday Polycarp
577A - Multiplication Table
817C - Really Big Numbers
1355A - Sequence with Digits
977B - Two-gram
993A - Two Squares